package com.ganbo.rabbitmq.producer.service;


import com.ganbo.rabbitmq.common.enums.MessageStatus;
import com.ganbo.rabbitmq.producer.config.DirectConfig;
import com.ganbo.rabbitmq.producer.config.TransactionCommitHandler;
import com.ganbo.rabbitmq.producer.entity.ProducerMessage;
import com.ganbo.rabbitmq.producer.repository.ProducerMessageRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class ProducerMessageService {

    @Autowired
    ProducerMessageRepository producerMessageRepository;
    @Autowired
    TransactionCommitHandler transactionCommitHandler;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Transactional
    public void send(String msg) {

        System.out.println("其他操作。。。");


        ProducerMessage message = new ProducerMessage();
        message.setContent(msg);
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);
        message.setStatus(MessageStatus.e1.getCode());
        String uuid = UUID.randomUUID().toString();
        message.setMessageId(uuid);

        producerMessageRepository.save(message);

        transactionCommitHandler.handle(() -> {
            //发送复审mq
            System.out.println("事务提交成功开始发送MQ消息======start");
            CorrelationData correlationData = new CorrelationData();
            correlationData.setId(uuid);
            rabbitTemplate.convertAndSend(DirectConfig.EXCHANGE_direct_direct, DirectConfig.routingKey, msg, correlationData);
            System.out.println("事务提交成功开始发送MQ消息======end");
        });
    }

    public void callBack(String messageId) {

        ProducerMessage message = producerMessageRepository.findByMessageId(messageId);
        message.setStatus(MessageStatus.e3.getCode());
        producerMessageRepository.saveAndFlush(message);
        log.info("消费者回调成功。。。。");

    }
}
